<template>
  <div class="ccui-app-container">
    <div class="ccui-advanced-search-wrapper ccui-clearfix">
      <el-search
        :formProp="formData"
        @search="search"
        @change="change"
        :isShowSearch="isShowSearch"
        class="ccui-highsearch"
        :selectClear="true"
      >
        <div class="ccui-tab-wrapper">
          <el-button type="table-top-active" size="mini"
            >全部({{ totalNum }})</el-button
          >
        </div>
        <el-export-button
          class="export-button"
          @export-excel="exportExcel"
          @export-pdf="exportPdf"
          style="display: inline-block; position: absolute; right: 0; top: 0"
        ></el-export-button>
        <template slot="search">
          <el-input
            v-model="formData.invoiceName"
            clearable
            searchLabel="发票单名称"
            placeholder="请输入发票单名称模糊查询"
          ></el-input>
          <el-input
            v-model="formData.invoiceCode"
            clearable
            searchLabel="发票单编号"
            placeholder="请输入发票单编号模糊查询"
          ></el-input>
          <el-input
            v-model="formData.settlementName"
            clearable
            searchLabel="结算单名称"
            placeholder="请输入结算单名称模糊查询"
          ></el-input>
          <el-input
            v-model="formData.settlementCode"
            clearable
            searchLabel="结算单编号"
            placeholder="请输入结算单编号模糊查询"
          ></el-input>
          <el-input
            v-model="formData.partyBName"
            clearable
            searchLabel="供应商"
            placeholder="请输入供应商模糊查询"
          ></el-input>

          <el-input
            v-model="formData.reportInOrgName"
            clearable
            searchLabel="填报单位"
            placeholder="请输入填报单位模糊查询"
          ></el-input>
          <el-select
            v-model="formData.enterStatus"
            clearable
            placeholder="请选择状态查询"
            searchLabel="状态"
            @change="handleContractState"
          >
            <el-option key="1" label="审批通过" value="5"></el-option>
            <el-option key="2" label="已冲销" value="22"></el-option>
          </el-select>
        </template>
        <el-input
          v-model="formData.invoiceName"
          clearable
          searchLabel="发票单名称"
          placeholder="请输入发票单名称模糊查询"
          slot="searchItem2"
        />
        <el-input
          v-model="formData.invoiceCode"
          clearable
          searchLabel="发票单编号"
          placeholder="请输入发票单编号模糊查询"
          slot="searchItem1"
        />
        <el-input
          v-model="formData.settlementName"
          clearable
          searchLabel="结算单名称"
          placeholder="请输入结算单名称模糊查询"
          slot="searchItem10"
        ></el-input>
        <el-input
          v-model="formData.settlementCode"
          clearable
          searchLabel="结算单编号"
          placeholder="请输入结算单编号模糊查询"
          slot="searchItem11"
        ></el-input>
        <el-input
          v-model="formData.partyBName"
          clearable
          searchLabel="供应商"
          placeholder="请输入供应商模糊查询"
          slot="searchItem3"
        />

        <el-input
          v-model="formData.reportInOrgName"
          clearable
          searchLabel="填报单位"
          placeholder="请输入填报单位模糊查询"
          slot="searchItem4"
        />
        <el-select
          v-model="formData.enterStatus"
          clearable
          placeholder="请选择状态查询"
          searchLabel="状态"
          @change="handleContractState"
          slot="searchItem5"
        >
          <el-option key="1" label="审批通过" value="5"></el-option>
          <el-option key="2" label="已冲销" value="22"></el-option>
        </el-select>
      </el-search>
    </div>
    <div class="ccui-multifunctional-table-wrapper">
      <el-table
        v-if="tableHack"
        ref="multipleTable"
        :data="tableData"
        :fit="true"
        :row-style="rowClass"
        @cell-click="cellClick"
        :cell-style="cellStyle"
        border
        class="ccui-multifunctional-table"
        @selection-change="handleSelectionChange"
        @header-dragend="tableTitleWidth"
        :min-height="9999"
      >
        <template v-for="(table, index) in tableTheadOptions">
          <el-table-column
            v-if="table.checked"
            :fixed="table.fixed || false"
            :type="table.type"
            :key="index"
            :label="table.label"
            :min-width="table.width"
            :prop="table.prop"
            :filters="table.filters"
            :formatter="formatterList[table.formatterName]"
            :align="table.align"
            :header-align="table.headerAlign || 'left'"
            :show-overflow-tooltip="true"
          ></el-table-column>
        </template>
      </el-table>
      <div class="ccui-table-footer" v-if="totalNum > 0">
        <div id="ccui-paging">
          <el-pagination
            :total="totalNum"
            :page-size="pageSizeCode"
            :current-page="pageNoCode"
            :page-sizes="[10, 20, 50, 100, 200, 500]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            popper-class="ccui-paging-page-size-popper"
            @prev-click="handlePrev"
            @next-click="handleNext"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <el-button
            class="ccui-pagination-btn"
            size="mini"
            type="default"
            @click="handleChangeSize('none')"
            >确定</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { listPageInvoiceBasicAccount } from "../api";
import {
  setSessionItem,
  getSessionItem,
  ishasAgentId
  // addUrlPerFix
} from "@/basa/utils";
import { getDetail, detailExport } from "@/basa/api";
import { exportData } from "@/basa/utils/public";
import { formatNumber } from "@/basa/utils";
export default {
  name: "invoiceParameterList",
  data() {
    return {
      orgId: null, //orgId
      formSearch: {},
      pageSizeCode: 1,
      pageNoCode: 1,
      //多页签
      focuses: [
        { focus: "Submit" },
        { focus: "Approval" },
        { focus: "ApprovalTurn" }
      ],
      workStatus: "",
      // 表格数据
      tableData: [],
      tableHack: true,
      // 表格命名
      tableName: this.tableList.invoiceParameterList,
      // 表格数据
      tableThead: [],
      // 锁定表格
      fixedTableThead: [
        {
          label: "序号",
          prop: "id",
          width: "38",
          checked: true,
          fixed: true,
          type: "index"
        },
        {
          label: "发票单编号",
          prop: "invoiceCode",
          width: "130",
          checked: true,
          fixed: true,
          align: "left"
        }
      ],
      // 非锁定表格
      unfixedTableThead: [
        {
          label: "发票单名称",
          prop: "invoiceName",
          width: "300",
          checked: true
        },
        {
          label: "供应商",
          prop: "partyBName",
          width: "200",
          checked: true
        },
        // {
        //   label: "合同签订单位",
        //   prop: "contractSignDeptName",
        //   width: "200",
        //   checked: true
        // },
        {
          label: "结算单编号",
          prop: "settlementCode",
          width: "150",
          checked: true
        },
        {
          label: "结算单名称",
          prop: "settlementName",
          width: "300",
          checked: true
        },
        {
          label: "填报单位",
          prop: "reportInOrgName",
          width: "200",
          checked: true
        },
        {
          label: "发票金额(含税)",
          prop: "currentInvoiceAmount",
          width: "140",
          checked: true,
          align: "right"
        },
        {
          label: "编制人",
          prop: "compileUser",
          width: "60",
          checked: true
        },
        {
          label: "编制日期",
          prop: "compileDate",
          width: "100",
          checked: true,
          formatterName: "compileDate"
        },
        {
          label: "不含税金额",
          prop: "amountExcludeTax",
          width: "130",
          checked: true,
          align: "right"
        },
        {
          label: "税额",
          prop: "tax",
          width: "130",
          checked: true,
          align: "right"
        },
        {
          label: "币种",
          prop: "currency",
          width: "130",
          checked: true
        },
        {
          label: "状态",
          prop: "enterStatus",
          width: "70",
          checked: true,
          formatterName: "enterStatus"
        },
        {
          label: "推送状态",
          prop: "pushStates",
          width: "80",
          checked: true,
          formatterName: ""
        },
        {
          label: "财务审核状态",
          prop: "finanAuditStates",
          width: "160",
          checked: true,
          formatterName: ""
        }
      ],
      //全部数量
      totalNum: 0,
      // 动态表格
      tableTheadOptions: [],
      // 弹框表格
      popoverShow: false,
      selectRow: [],
      selectData: [],
      // 高级搜索数据 start
      // 高级搜索提交数据
      isShowSearch: true,
      formData: {
        invoiceCode: "",
        invoiceName: "",
        partyBName: "",
        reportInOrgName: "",
        enterStatus: "",
        settlementCode: "",
        settlementName: "",
        // invoiceStatus:'',
        pageNo: 1,
        // pageSize: this.getLocalPageSize(),
        pageSize: 10,
        isShowPageLoading: true
      },
      formatterList: {
        enterStatus(row) {
          switch (row.enterStatus) {
            case "2":
              return "待提交";
            case "3":
              return "审批中";
            case "4":
              return "已撤回";
            case "5":
              return "审批通过";
            case "6":
              return "审批退回";
            case "22":
              return "已冲销";
          }
        },
        compileDate(row) {
          if (row.compileDate) {
            let newCompileDate = row.compileDate.substring(0, 10);
            return newCompileDate;
          }
        }
      },
      enterStatus: "",
      formDataSearch: "",
      // formDataSearch:{
      //     invoiceCode: "",
      //     invoiceName: "",
      //     partyBName: "",
      //     reportInOrgName: "",
      //     enterStatus: "",
      //     // invoiceStatus:'',
      //     // pageNo: 1,
      //     // pageSize: this.getLocalPageSize(),
      //     isShowPageLoading: true
      // },
      // 高级搜索数据 end
      content: "",
      smpScStatusTypeName: {
        5: "审批通过",
        22: "已冲销"
      }
    };
  },
  activated() {
    this.formData = {
      invoiceCode: "",
      invoiceName: "",
      partyBName: "",
      reportInOrgName: "",
      enterStatus: "",
      settlementName: "",
      settlementCode: ""
    };
    this.formData.pageNo = 1;
    this.pageNoCode = 1;
    this.formSearch = {};
    this.getDetail();
  },

  mounted() {
    this.initData();
    let tableTime = this.getDate();
    this.content = "导出日期:" + tableTime;
    // this.getDetail();
  },
  methods: {
    getDetail() {
      getDetail({}).then(res => {
        if (res.data.code == 0) {
          this.orgId = res.data.data.orgId;
          this.formData.reportOrgId = res.data.data.orgId;
          this.getParameterList(); //请求列表
        }
      });
    },
    initData() {
      this.setTableWidth();
      this.renderTable();
    },
    change(index, key, value) {
      const formDataKeys = Object.keys(this.formData);
      formDataKeys.map(_ => {
        if (_ !== key) this.formData[_] = "";
      });
    },
    // 获取时间方法
    getDate() {
      let date = new Date();
      let seperator1 = "-";
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },
    formPageNo(val) {
      return Number(val);
    },
    //合同状态
    handleContractState(data) {
      if (data) {
        this.enterStatus = data;
        this.formData.enterStatus = data;
        console.log(this.formData.enterStatus);
      }
    },

    //查列表getParameterList
    getParameterList(reqObj) {
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.pageNo = this.pageNoCode;
      obj.pageSize = this.pagesize;
      listPageInvoiceBasicAccount({
        // ...this.formData,
        ...obj,
        reportInAuthCode: "underOrg"
      }).then(res => {
        if (res.data.code == 0) {
          this.tableData = res.data.data.rows;
          this.tableData.forEach((item, index) => {
            index = 1 + index;
            if (item.compileDate) {
              item.compileDate = item.compileDate.substring(0, 10);
            }
            item.currentInvoiceAmount = formatNumber(
              item.currentInvoiceAmount,
              2
            );
            item.tax = formatNumber(item.tax, 2);
            item.amountExcludeTax = formatNumber(item.amountExcludeTax, 2);
          });
          this.totalNum = res.data.data.recordsTotal;
        } else {
          this.$message({
            message: res.data.message,
            type: "success",
            showClose: true,
            ccuiCustom: true
          });
        }
      });
    },
    // 根据返回状态显示不同的文字颜色
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "transparent" };
      }
      if (columnIndex == 1) {
        return { color: "#0089EF", cursor: "pointer" };
      }
    },
    // 默认渲染表格
    renderTable() {
      const localTableData = localStorage.getItem(this.tableName)
        ? JSON.parse(localStorage.getItem(this.tableName))
        : [];
      console.log(localTableData);
      let unfixedTableThead = this.fixedTableThead.concat(
        this.unfixedTableThead
      );
      let localTableDataStr = localTableData.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );
      let unfixedTableTheadStr = unfixedTableThead.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );

      if (localTableData.length === unfixedTableThead.length) {
        let flag = localTableDataStr.every(item =>
          unfixedTableTheadStr.includes(item)
        );
        if (flag) {
          // 完全相同
          this.tableTheadOptions = localTableData;
          this.tableThead = localTableData;
          localTableData.forEach(item => {
            let index = this.unfixedTableThead.findIndex(
              cItem => item.prop === cItem.prop
            );
            index !== -1 &&
              (this.unfixedTableThead[index].checked = item.checked);
          });
        } else {
          // 长度相同但值不同
          this.tableThead = this.fixedTableThead.concat(this.unfixedTableThead);
          const comment = JSON.stringify(this.tableThead);
          localStorage.setItem(this.tableName, comment);
          const localTableData = JSON.parse(
            localStorage.getItem(this.tableName)
          );
          this.tableTheadOptions = localTableData;
        }
      } else {
        // 长度不同
        this.tableThead = this.fixedTableThead.concat(this.unfixedTableThead);
        const comment = JSON.stringify(this.tableThead);
        localStorage.setItem(this.tableName, comment);
        const localTableData = JSON.parse(localStorage.getItem(this.tableName));
        this.tableTheadOptions = localTableData;
      }
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      console.log(this.unfixedTableThead);
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (this.unfixedTableThead[i].label === column.label) {
          this.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      console.log(this.tableTheadOptions);
      this.tableHack = false;
      this.$nextTick(() => {
        this.tableHack = true;
      });
    },
    handleSelectionChange(data) {
      this.selectData = data;
    },
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "rgba(255,232,195,1) " };
      }
    },
    // 查看
    cellClick(row, column, columnIndex) {
      if (column.label === "发票单编号") {
        this.$router.push({
          path: "/invoice/invoiceParameter/list-detail",
          query: {
            id: row.id,
            invoiceName: row.invoiceName,
            enterStatus: row.enterStatus
          }
        });
      }
    },
    // 分页
    // 上一页
    handlePrev() {},
    // 下一页
    handleNext() {},
    //  显示条数更改
    handleSizeChange(val) {
      // this.formData.pageNo = 1;
      this.pageNoCode = 1;
      this.pagesize = val;
      this.formData.pageSize = val;
      setSessionItem("pageSize", this.tableName, val);
      if (this.enterStatus) {
        this.formData.enterStatus = this.enterStatus;
      } else {
        this.formData.enterStatus = "";
      }
      this.getParameterList(this.formSearch);
      // this.search(this.formSearch)
    },
    //翻页确定
    handleChangeSize() {
      if (this.enterStatus) {
        this.formData.enterStatus = this.enterStatus;
      } else {
        this.formData.enterStatus = "";
      }
      this.getParameterList(this.formSearch);
      // this.search(this.formSearch)
    },
    // 获取默认条数
    getLocalPageSize() {
      return (
        getSessionItem("pageSize", this.tableList.invoiceParameterList) || 10
      );
    },
    // 当前页码更改
    handleCurrentChange(val) {
      console.log("iop", val);
      // 跳转翻页都会调这个方法
      // this.formData.pageNo = val;
      this.pageNoCode = val;
      this.formSearch.pageNo = val;
      if (this.enterStatus) {
        this.formData.enterStatus = this.enterStatus;
      } else {
        this.formData.enterStatus = "";
      }
      this.getParameterList(this.formSearch);
      // this.search(this.formSearch)
      // console.log("this.formSearch",this.formSearch);
    },
    // 分页 end
    // 高级搜索所需函数 start
    // 高级搜索展开按钮
    search(searchData) {
      console.log(searchData);
      this.formSearch = searchData;
      //   this.formData = JSON.parse(JSON.stringify(searchData));
      if (Object.keys(searchData).length !== 0) {
        this.formData = JSON.parse(JSON.stringify(searchData));
        if (this.formData.undefined) {
          delete this.formData.undefined;
        }
      }
      //   if (searchData.invoiceStatus!=='') {
      //     this.formData.enterStatus = this.formData.invoiceStatus;
      //   }
      this.pageNoCode = 1;
      // this.formData.pageNo = 1;
      this.formData.isShowPageLoading = true;
      // this.formData.pageSize = this.getLocalPageSize();
      this.formData.pageSize = this.pageSize;

      //   }else{
      //       const aaa={
      //     invoiceCode: "",
      //     invoiceName: "",
      //     partyBName: "",
      //     reportInOrgName: "",
      //     enterStatus: "5,22",
      //     invoiceStatus:'',
      //     pageNo: 1,
      //     pageSize: 20,
      //     isShowPageLoading: true
      //   }
      //       console.log(aaa)
      //       this.formData.enterStatus=aaa.enterStatus
      //      console.log(this.formData.enterStatus)
      //   }
      this.getParameterList(searchData);
    },
    // 高级搜索 end
    // 导出当前
    exportExcel() {
      let formDataSearch = JSON.parse(JSON.stringify(this.formData));
      delete formDataSearch.isShowPageLoading;

      detailExport({
        ...formDataSearch,
        type: "invocebasic/accountExport"
      }).then(res => {
        exportData(res);
      });
      // accountExport({
      //   ...formDataSearch,
      //   reportInAuthCode: "underOrg"
      //   // pageNo: this.pageNo,
      //   // pageSize: this.pageSize,
      // }).then(res => {
      //   if (res.data.code) {
      //     let a = document.createElement("a");
      //     a.style.display = "none";
      //     a.href = `${addUrlPerFix(
      //       process.env.VUE_APP_BASE_URL
      //     )}/apis/smp/oss/downloadByUploadId?uploadId=${
      //       res.data.data.fileRspBo.uploadId
      //     }`;
      //     a.setAttribute("download", res.data.data.fileRspBo.fileName);
      //     document.body.appendChild(a);
      //     a.click();
      //   }
      // });
    },

    // 导出全部
    exportPdf() {
      let formDataSearch = JSON.parse(JSON.stringify(this.formData));
      formDataSearch.pageNo = 1;
      formDataSearch.pageSize = 3000;
      delete formDataSearch.isShowPageLoading;

      detailExport({
        ...formDataSearch,
        type: "invocebasic/accountExport"
      }).then(res => {
        exportData(res);
      });
    }
  },
  beforeRouteLeave(to, from, next) {
    for (var key in this.$vnode.parent.parent.componentInstance.cache) {
      delete this.$vnode.parent.parent.componentInstance.cache[
        ishasAgentId(to.path, key)
      ];
    }
    next();
  }
};
</script>
<style lang="scss" scoped>
/deep/ #ccui-paging .ccui-pagination-btn {
  display: block;
}
/deep/ .el-search .el-searchs-box {
  margin-right: 70px;
}

/deep/.ccui-advanced-search-wrapper
  .el-search
  .ccui-search-wrapper
  .el-searchs
  .el-searchs-right
  .el-input__inner {
  padding: 0 8px 0 0 !important;
}
</style>
